<template>
    <div class="h-max-content" :id="id">
        <tiny-base-select ref="componentRef" v-bind="$attrs" :options="$attrs.options || options" v-on="events">
            <template #[name] v-for="_slot, name in $slots">
                <slot :name="name"></slot>
            </template>
            <template #footer v-if="!$slots.footer && isPager">
                <div class="flex-center">
                    <tiny-pager :total="total" @before-page-change="getData" is-before-page-change></tiny-pager>
                </div>
            </template>
        </tiny-base-select>
    </div>
</template>

<script setup lang="ts">
import { useComponentExpose } from '@/hooks/useComponentExpose';
import type { TinyBaseSelect } from '@opentiny/vue';
import { useId } from 'vue';
import { onMounted, useAttrs } from 'vue';
import { ref } from 'vue';
const id = useId()

const props = defineProps({
    api: {
        type: Function,
        required: true
    },
    params: {
        type: Object,
        default: () => ({}),
    },
    attr: {
        type: Object,
        default: () => ({
            label: 'label',
            value: 'id',
            children: 'children',
        }),
    },
    isPager: {
        type: Boolean,
        default: false,
    },
});
const { componentRef, exposed } = useComponentExpose<InstanceType<typeof TinyBaseSelect>>({
    reload() {
        getData();
    }
})
const total = ref(0);
const attrs = useAttrs()
const options = ref([]);
// const value = ref(attrs.multiple ? [] : '');
const events = ref<Record<string, any>>({});
Object.keys(attrs).forEach((key) => {
    if (key.startsWith('on')) {
        events.value[key.slice(2)] = attrs[key];
    }
});
const loading = ref(false);
type Pager = {
    currentPage: number,
    currentPageSize: number
    newPage: number,
    newPageSize: number
    callback: () => void
}
async function getData(page?: Pager) {
    loading.value = true;
    if (props.api && typeof props.api === 'function') {
        const params = {
            ...props.params,
        };
        if (props.isPager) {
            const { newPage = 1, newPageSize = 10, callback } = page || { newPage: 1, newPageSize: 10 };
            params.page = newPage - 1;
            params.size = newPageSize;
            callback && callback()
        }
        props
            .api(params, { uniqueId: id })
            .then(
                ({ data }: R) => {
                    options.value = data.dataList.map((item: any) => {
                        return {
                            ...item,
                            label: item[props.attr.label],
                            value: item[props.attr.value],
                        };
                    });
                    total.value = data.totalCount;
                },
                (err: any) => {
                    console.error(err);
                    console.error('获取数据失败');
                    options.value = []
                }
            )
            .finally(() => {
                loading.value = false;
            });
    } else {
        loading.value = false;
        options.value = []

    }
}

onMounted(() => {
    getData();
})

defineExpose(exposed)
</script>

<style scoped></style>